/**
 * Copyright (c) 2024 Hunan OpenValley Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "GPUImageHighlightShadowFilter.h"

const std::string
    GPUImageHighlightShadowFilter::HIGHLIGHT_SHADOW_FRAGMENT_SHADER = R"(
    #extension GL_OES_EGL_image_external : require
    uniform samplerExternalOES inputImageTexture;
    varying highp vec2 textureCoordinate;
    
    uniform lowp float shadows;
    uniform lowp float highlights;
    
    const mediump vec3 luminanceWeighting = vec3(0.3, 0.3, 0.3);
    
    void main()
    {
        lowp vec4 source = texture2D(inputImageTexture, textureCoordinate);
        mediump float luminance = dot(source.rgb, luminanceWeighting);
        
        mediump float shadow = clamp((pow(luminance, 1.0/(shadows+1.0)) + (-0.76)*pow(luminance, 2.0/(shadows+1.0))) - luminance, 0.0, 1.0);
        mediump float highlight = clamp((1.0 - (pow(1.0-luminance, 1.0/(2.0-highlights)) + (-0.8)*pow(1.0-luminance, 2.0/(2.0-highlights)))) - luminance, -1.0, 0.0);
        lowp vec3 result = vec3(0.0, 0.0, 0.0) + ((luminance + shadow + highlight) - 0.0) * ((source.rgb - vec3(0.0, 0.0, 0.0))/(luminance - 0.0));
        
        gl_FragColor = vec4(result.rgb, source.a);
    }
)";

GPUImageHighlightShadowFilter::GPUImageHighlightShadowFilter()
    : shadows(0.0f), highlights(1.0f) {}

GPUImageHighlightShadowFilter::GPUImageHighlightShadowFilter(
    float shadowsVal, float highlightsVal)
    : GPUImageFilter(NO_FILTER_VERTEX_SHADER,
                     HIGHLIGHT_SHADOW_FRAGMENT_SHADER)
{
    highlights = highlightsVal;
    shadows = shadowsVal;
}

void GPUImageHighlightShadowFilter::onInit()
{
    GPUImageFilter::onInit();
    highlightsLocation = glGetUniformLocation(getProgram(), "highlights");
    shadowsLocation = glGetUniformLocation(getProgram(), "shadows");
}

void GPUImageHighlightShadowFilter::onInitialized()
{
    GPUImageFilter::onInitialized();
    setHighlights(highlights);
    setShadows(shadows);
}

void GPUImageHighlightShadowFilter::setHighlights(float highlightsVal)
{
    highlights = highlightsVal;
    setFloat(highlightsLocation, highlights);
}

void GPUImageHighlightShadowFilter::setShadows(float shadowsVal)
{
    shadows = shadowsVal;
    setFloat(shadowsLocation, shadows);
}